
package com.kanjian.music.activity;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.kanjian.music.R;
import com.kanjian.music.api.ApiRequestManager;
import com.kanjian.music.config.OpenConfig;
import com.kanjian.music.constants.IntentConstants;
import com.kanjian.music.entity.BaseCode;
import com.kanjian.music.entity.User;
import com.kanjian.music.network.HttpLoader;
import com.kanjian.music.util.ThirdPartyShareUtil;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.UsersAPI;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.tencent.utils.HttpUtils.HttpStatusException;
import com.tencent.utils.HttpUtils.NetworkUnavailableException;

public class RegisterActivity extends BaseActivity implements LoaderCallbacks<String> {

    private EditText mEdit_userName;

    private EditText mEdit_password;

    private Button mBtn_register;

    private Button mBtn_weibo;

    private Button mBtn_qqConnect;

    private final int REQUESTCODE_CHECKUSERNAME = 0;

    private final int REQUESTCODE_REGISTER = 1;

    private Tencent mTencent;

    private WeiboAuth mWeiboAuth;

    private SsoHandler mSSoHandler;

    private Oauth2AccessToken mAccessToken;

    @Override
    protected void onCreate(Bundle arg0) {
        setContentView(R.layout.activity_register);
        super.onCreate(arg0);
        initView();
        mTencent = Tencent
                .createInstance(OpenConfig.QQ_CONNECT_APPID, this.getApplicationContext());
    }

    private void initView() {
        mEdit_userName = (EditText) findViewById(R.id.register_username);
        mEdit_password = (EditText) findViewById(R.id.register_password);
        mBtn_register = (Button) findViewById(R.id.register_btn);
        mBtn_register.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Bundle b = new Bundle();
                b.putSerializable(IntentConstants.HTTPLOADERREQUESTPARAM, ApiRequestManager
                        .getCheckUserNameRequest(mEdit_userName.getText().toString()));
                getSupportLoaderManager().restartLoader(REQUESTCODE_CHECKUSERNAME, b,
                        RegisterActivity.this);
            }
        });
        mBtn_weibo = (Button) findViewById(R.id.register_open_weibo);
        mBtn_weibo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mWeiboAuth = new WeiboAuth(RegisterActivity.this, OpenConfig.WEIBO_APP_KEY,
                        OpenConfig.REDIRECT_URL, OpenConfig.WEIBO_SCOPE);
                mSSoHandler = new SsoHandler(RegisterActivity.this, mWeiboAuth);
                mSSoHandler.authorize(new AuthListener());

                // ThirdPartyShareUtil.ShareToWeibo(RegisterActivity.this);
                // ThirdPartyShareUtil.ShareToMMCircle(RegisterActivity.this);
                // ThirdPartyShareUtil.ShareToMMFriend(RegisterActivity.this);

            }
        });
        mBtn_qqConnect = (Button) findViewById(R.id.register_open_qq_connect);
        mBtn_qqConnect.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTencent != null) {
                    mTencent.login(RegisterActivity.this, "all", new BaseUiListener());
                }
            }
        });

    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object obj) {
            if (obj != null && obj instanceof JSONObject) {
                doComplete((JSONObject) obj);
            }
        }

        @Override
        public void onError(UiError e) {
        }

        @Override
        public void onCancel() {
            System.out.println("cancel");
        }

        private void doComplete(JSONObject jobj) {
            try {
                System.out.println(jobj);
                final String openId = jobj.getString("openid");
                final String accessToken = jobj.getString("access_token");
                final String expiresIn = jobj.getString("expires_in");
                if (!TextUtils.isEmpty(openId) && !TextUtils.isEmpty(accessToken)) {
                    mTencent.setOpenId(openId);
                    mTencent.setAccessToken(accessToken, expiresIn);

                    // {"is_yellow_year_vip":"0","ret":0,"figureurl_qq_1":"http:\/\/q.qlogo.cn\/qqapp\/100363672\/2386D0CA0499BA6B286075F2414C1A22\/40","figureurl_qq_2":"http:\/\/q.qlogo.cn\/qqapp\/100363672\/2386D0CA0499BA6B286075F2414C1A22\/100","nickname":"奥特","yellow_vip_level":"0","is_lost":0,"msg":"","figureurl_1":"http:\/\/qzapp.qlogo.cn\/qzapp\/100363672\/2386D0CA0499BA6B286075F2414C1A22\/50","vip":"0","level":"0","figureurl_2":"http:\/\/qzapp.qlogo.cn\/qzapp\/100363672\/2386D0CA0499BA6B286075F2414C1A22\/100","is_yellow_vip":"0","gender":"男","figureurl":"http:\/\/qzapp.qlogo.cn\/qzapp\/100363672\/2386D0CA0499BA6B286075F2414C1A22\/30"}

                    new Thread() {
                        public void run() {
                            try {
                                Bundle b = new Bundle();
                                b.putString("access_token", accessToken);
                                b.putString("oauth_consumer_key", "100363672");
                                b.putString("openid", openId);
                                JSONObject o = mTencent.request("user/get_simple_userinfo", b,
                                        Constants.HTTP_GET);
                                if (o != null) {
                                    String nickName = o.getString("nickname");
                                    Bundle args = new Bundle();
                                    args.putSerializable(IntentConstants.HTTPLOADERREQUESTPARAM,
                                            ApiRequestManager.getOpenRegisterRequest(openId,
                                                    "tencent", accessToken, expiresIn, nickName));
                                    getSupportLoaderManager().restartLoader(1, args,
                                            RegisterActivity.this);
                                }
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (NetworkUnavailableException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (HttpStatusException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        };
                    }.start();

                    // ApiRequestManager.getOpenRegisterRequest(openId, from,
                    // accessToken, expireTime, uName)
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Loader<String> onCreateLoader(int id, Bundle args) {
        return new HttpLoader(this, args);
    }

    @Override
    public void onLoadFinished(Loader<String> loader, String data) {
        Toast.makeText(this, data, 1).show();
        if (loader.getId() == 0) {
            if (data != null) {
                if (loader.getId() == REQUESTCODE_CHECKUSERNAME) {
                    BaseCode checkUserNameCode = BaseCode.getCommonCodeFromString(data);
                    if (checkUserNameCode.mErrorCode != 20000) {
                        Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show();
                    } else {
                        Bundle b = new Bundle();
                        b.putSerializable(IntentConstants.HTTPLOADERREQUESTPARAM, ApiRequestManager
                                .getRegisterRequest(mEdit_userName.getText().toString(),
                                        mEdit_password.getText().toString()));
                        getSupportLoaderManager().restartLoader(REQUESTCODE_REGISTER, b, this);
                    }
                } else if (loader.getId() == REQUESTCODE_REGISTER) {
                    User user = User.getUserFromJson(data);
                    if (user.mErrorCode == 20000) {
                        User.localLogin(data);
                        Toast.makeText(this, "success", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            }
        } else if (loader.getId() == 1) {
            System.out.println(data);
        }
    }

    @Override
    public void onLoaderReset(Loader<String> loader) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mTencent != null) {
            mTencent.onActivityResult(requestCode, resultCode, data);
        }
        if (mSSoHandler != null) {
            mSSoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    class AuthListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle values) {
            // 从 Bundle 中解析 Token
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            if (mAccessToken.isSessionValid()) {
                // String nickName = o.getString("nickname");
                UsersAPI userApi = new UsersAPI(mAccessToken);
                userApi.show(Long.parseLong(mAccessToken.getUid()), weiboApiListener);
            } else {
                // 以下几种情况，您会收到 Code：
                // 1. 当您未在平台上注册的应用程序的包名与签名时；
                // 2. 当您注册的应用程序包名与签名不正确时；
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                String code = values.getString("code");
                if (!TextUtils.isEmpty(code)) {
                }
            }
        }

        @Override
        public void onCancel() {
        }

        @Override
        public void onWeiboException(WeiboException e) {
        }
    }

    private RequestListener weiboApiListener = new RequestListener() {

        @Override
        public void onWeiboException(WeiboException e) {
            //TODO: 让小姚添加测试账号
            System.out.println(e);
        }

        @Override
        public void onComplete(String data) {
            com.sina.weibo.sdk.openapi.models.User user = com.sina.weibo.sdk.openapi.models.User.parse(data);
            if (user != null) {
                Bundle args = new Bundle();
                args.putSerializable(IntentConstants.HTTPLOADERREQUESTPARAM, ApiRequestManager
                        .getOpenRegisterRequest(OpenConfig.WEIBO_APP_KEY, "weibo",
                                mAccessToken.getToken(), mAccessToken.getExpiresTime() + "",
                                user.name));
                getSupportLoaderManager().restartLoader(1, args, RegisterActivity.this);
            }
        }
    };

}
